package com.wanqing.community.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wanqing.community.util.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.wanqing.community.bean.MenuBean;
import com.wanqing.community.bean.MenuOperateBean;
import com.wanqing.community.bean.UserBean;
import com.wanqing.community.bean.UserDetailBean;
import com.wanqing.community.controller.util.BaseController;
import com.wanqing.community.manager.MenuManager;
import com.wanqing.community.manager.UserDetailManager;
import com.wanqing.community.bean.JsonTree;

/**
 * 菜单管理的Controller
 * Copyright 2014 XXX Co.Ltd.
 * All right reserved.
 * @author LY
 * @version 
 * Company XX公司
 */
@Controller
@RequestMapping("menuContorller")
public class MenuController extends BaseController{
	
	private static Logger log = Logger.getLogger(MenuController.class);

	@Resource
	private MenuManager menuManager;
	@Resource
	private UserDetailManager userDetailManager;
	
	/**
	 * <p>Description:产生导航菜单<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LY
	 * @modifiDate 2014-9-16
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/queryNavigationMenu")
	public String queryNavigationMenu(HttpServletRequest request,HttpServletResponse response){
		try{			
			String action = request.getParameter("action");			
			if(action.equals("list")){//获取属面板列表
				ConditionParse condParse = new ConditionParse();
				condParse.addCondition("MPID", "=", "000");
				condParse.addWhereStr();
				List<JsonTree> rows = this.menuManager.queryNavigationMenu(condParse);
				String json = StringTools.buildJson(rows, false);
				writeJson(response, json);				
			}else if(action.equals("node")){
				String pid = request.getParameter("id");
				ConditionParse condParse = new ConditionParse();
				condParse.addCondition("MPID", "=", pid);
				condParse.addWhereStr();
				List<JsonTree> rows = this.menuManager.queryNavigationMenu(condParse);
				String json = StringTools.buildJson(rows, false);
				writeJson(response, json);
			}else if(action.equals("tree")){
				String tid = request.getParameter("tid");				
				if(StringTools.isEmptyOrNull(tid) || "root".equals(tid)){
					tid="-1";
				}
				ConditionParse condParse = new ConditionParse();
				condParse.addCondition("MPID", "=", tid);
				condParse.addWhereStr();				
				List<MenuBean> rows = this.menuManager.queryMenu(condParse);
				List<JsonTree> list = new ArrayList<JsonTree>();
				JsonTree tree = null;
				for (MenuBean menu : rows) {
					tree = new JsonTree();
					tree.setId(menu.getMid());
					tree.setText(menu.getMname());
					tree.setPid(menu.getMpid());
					tree.setCode(menu.getMcode());
					tree.setDepth(menu.getMdepth());					
					tree.setState(menu.isMleaf()?"open":"closed");
					String iconCls = menu.getIconCls();
					if(!StringTools.isEmptyOrNull(iconCls)){
						iconCls = "icon "+iconCls;
					}
					tree.setIconCls(iconCls);									
					list.add(tree);
				}				
				String json = StringTools.buildJson(list,false);				
				writeJson(response, json);
			}
		}catch (Exception e) {
			log.error("查询菜单数据，生成菜单管理中的树形异常："+e.toString());
		}
		return null;
	}
	
	/**
	 * <p>Description:查询菜单列表<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LY
	 * @modifiDate 2014-9-16
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/queryMenu")
	public String queryMenu(HttpServletRequest request,HttpServletResponse response){
		try{
			int pageNo = NumberDealTools.stringTranceInt(request.getParameter("page"), 1);
			int pageSize = NumberDealTools.stringTranceInt(request.getParameter("rows"), KeyConstant.PAGESIZE);
			ConditionParse condParse = new ConditionParse();
			String id = request.getParameter("Id");
			if(StringTools.isNotEmptyOrNull(id)){
				condParse.addCondition("MPID", "=", id);
			}else{
				condParse.addCondition("MPID", "=", "000");
			}
			condParse.addWhereStr();
			int total = this.menuManager.getMenuCount(condParse);
			List<MenuBean> list = this.menuManager.queryMenu(condParse, pageNo, pageSize);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);	
			String json = StringTools.buildJson(map);			
			writeJson(response, json);
		}catch (Exception e) {
			log.error("查询菜单数据，生成菜单管理中的树形异常："+e.toString());
		}
		return null;
	}
	
	/**
	 * <p>Description:添加菜单<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LY
	 * @modifiDate 2014-9-16
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=addMenu")
	public String addMenu(HttpServletRequest request,HttpServletResponse response){
		try{			 
			String p_mcode = StringTools.objectToString(request.getParameter("p_mcode"));
			String p_mdepth = StringTools.objectToString(request.getParameter("p_mdepth"));
			String mname = StringTools.objectToString(request.getParameter("mname"));
			String mpid = StringTools.objectToString(request.getParameter("mpid"));			
			MenuBean mb = new MenuBean();
			String menuId = UUID.uuId();
			String micon = StringTools.objectToString(request.getParameter("micon"));
			String miconno = "";
			/*if(StringTools.isNotEmptyOrNull(micon)){
				String[] fname = FileTools.fileName(micon);
				miconno = fname[0]+"_no"+".png";
			}	*/		
			mb.setMid(menuId);
			//mb.setMcode(menuId);
			mb.setMname(mname);
			mb.setMstate(StringTools.objectToString(request.getParameter("mstate")));
			mb.setMurl(StringTools.objectToString(request.getParameter("murl"),""));
			mb.setMicon(micon);
			mb.setMiconno(miconno);
			mb.setMpid(mpid);
			mb.setPhoneIcon(StringTools.objectToString(request.getParameter("phoneIcon"),""));
			mb.setWinIcon(StringTools.objectToString(request.getParameter("winIcon"),""));
			mb.setMremark(StringTools.objectToString(request.getParameter("mremark"),""));
			mb.setIconCls(StringTools.objectToString(request.getParameter("iconCls")));			
			mb.setSeqnum(NumberDealTools.stringTranceInt(StringTools.objectToString(request.getParameter("seqnum")),1));
			MenuBean pmb = new MenuBean();
			pmb.setMcode(p_mcode);
			pmb.setMdepth(NumberDealTools.stringTranceInt(p_mdepth));
			pmb.setMpid(mpid);
			mb.setParentMenu(pmb);
			
			int jobline = NumberDealTools.stringTranceInt(StringTools.objectToString(request.getParameter("jobline")));
			int len = jobline+1;			
			List<MenuOperateBean> listoperates = new ArrayList<MenuOperateBean>();
			MenuOperateBean mob = null;
			for(int i = 0; i < len; i++){
				String opername = StringTools.objectToString(request.getParameter("name"+i));
				if(!StringTools.isEmptyOrNull(opername)){
					String opercode = StringTools.objectToString(request.getParameter("code"+i));
					String operevent = StringTools.objectToString(request.getParameter("event"+i),"");
					String operestate = StringTools.objectToString(request.getParameter("state"+i));
					String opereseqnum = StringTools.objectToString(request.getParameter("operseqnum"+i));
					String opertype = StringTools.objectToString(request.getParameter("opertype"+i));
					String opereremark = StringTools.objectToString(request.getParameter("remark"+i),"");
					String operIconCls = StringTools.objectToString(request.getParameter("iconCls"+i),"");
					if(StringTools.isEmptyOrNull(operIconCls) && "FUNTREE".equalsIgnoreCase(opertype)){
						operIconCls = "icon-add";
					}
					mob = new MenuOperateBean();
					mob.setOperId(UUID.uuId());
					mob.setMenuId(menuId);
					mob.setOperatename(opername);
					mob.setOperatecode(opercode);
					mob.setOperateevent(operevent);
					mob.setOperatestate(NumberDealTools.stringTranceInt(operestate));
					mob.setOperseqnum(NumberDealTools.stringTranceInt(opereseqnum));
					mob.setOpertype(opertype);
					mob.setOperateremark(opereremark);
					mob.setOperateIconCls(operIconCls);
					listoperates.add(mob);
				}
			}
			mb.setListoperates(listoperates);			
			boolean b = menuManager.addMenu(mb);
			if(b){
				writeText(response,  KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {			
			log.error(e.toString());
			writeText(response, e.toString());		
		}		
		return null;
	}
	
	/**
	 * <p>Description:查询所有的菜单数据<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LGH
	 * @modifiDate 2014-7-2
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=listMenu")
	public ModelAndView listMenu(HttpServletRequest request,HttpServletResponse response){
		ModelAndView mav = new ModelAndView();
		try{
			UserBean user = this.getLoginUser(request);
			List<UserDetailBean> udList = this.userDetailManager.findUserDetailById(user.getId());
			List<MenuBean> menuList = new ArrayList<MenuBean>();
			Map<String,List<MenuOperateBean>> funcopreaTemp = new HashMap<String,List<MenuOperateBean>>();
			Map<String,List<MenuOperateBean>> buissopreaTemp = new HashMap<String,List<MenuOperateBean>>();
			
			int size=udList.size(); 
			String[] roleIdArray = new String[size]; 
			for(int i=0;i<size;i++){
				String roleId = udList.get(i).getRoleId();
				roleIdArray[i] = roleId;
				//用户对应的按钮权限
				funcopreaTemp = menuManager.queryFuncOperate(roleId);
				//用户对应的业务权限
				buissopreaTemp = menuManager.queryBuisOperate(roleId);
			}
			menuList = this.menuManager.queryAclMenu(roleIdArray);
			
			HttpSession session = request.getSession();
			session.setAttribute(KeyConstant.LIST_MAIN_MENU, menuList);
			session.setAttribute(KeyConstant.FUNC_MENU_BUISS, buissopreaTemp);
			session.setAttribute(KeyConstant.FUNC_MENU_FUNTREE, funcopreaTemp);
			mav.setView(new RedirectView("pages/main.jsp"));
		}catch (Exception e) {			
			log.error(e.toString());
			mav.addObject(KeyConstant.EXCEPTIONS, e.toString());
			mav.setViewName(KeyConstant.EXCEPTION_PAGE);
		}
		return mav;
	}
	
	/**
	 * <p>Description:查询菜单的对应的操作功能<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LY
	 * @modifiDate 2014-9-16
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return 
	 */
	@RequestMapping(params="method=findMenu")
	public ModelAndView findMenu(HttpServletRequest request,HttpServletResponse response){	
		ModelAndView mav = new ModelAndView();
		try{			
			String menuId = request.getParameter("menuId");
			String pname = request.getParameter("pname");	
			MenuBean menu = this.menuManager.findMenuById(menuId);
			mav.addObject("menu", menu);
			mav.addObject("pname", pname);
			mav.setViewName("sys/menu/updateMenu");
		}catch (Exception e) {
			log.error(e.toString());
			mav.addObject(KeyConstant.EXCEPTIONS, e.toString());
			mav.setViewName(KeyConstant.EXCEPTION_PAGE);
		}		
		return mav;
	}
	
	/**
	 * <p>Description:显示菜单及功能详细<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LY
	 * @modifiDate 2014-9-16
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=viewDetailMenu")
	public ModelAndView viewDetailMenu(HttpServletRequest request,HttpServletResponse response){	
		ModelAndView mav = new ModelAndView();
		try{			
			String menuId = request.getParameter("menuId");
			String pname = request.getParameter("pname");	
			MenuBean menu = this.menuManager.findMenuById(menuId);
			mav.addObject("menu", menu);
			mav.addObject("pname", pname);
			mav.setViewName("sys/menu/viewMenu");
		}catch (Exception e) {
			log.error(e.toString());
			mav.addObject(KeyConstant.EXCEPTIONS, e.toString());
			mav.setViewName(KeyConstant.EXCEPTION_PAGE);
		}		
		return mav;
	}
	
	/**
	 * <p>Description:修改菜单<p>
	 * @author LY
	 * @version 2014-7-17
	 * @modifier LY
	 * @modifiDate 2014-7-17
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=updateMenu")
	public String updateMenu(HttpServletRequest request,HttpServletResponse response){
		try{			
			MenuBean mb = new MenuBean();
			String menuId = StringTools.objectToString(request.getParameter("mid"));
			mb.setMid(menuId);
			String micon = StringTools.objectToString(request.getParameter("micon"));
			String miconno = "";			
			String leaf = StringTools.objectToString(request.getParameter("mleaf"));			
			boolean mleaf = StringTools.stringToBoolean(leaf);
			mb.setMleaf(mleaf);
			mb.setMname(StringTools.objectToString(request.getParameter("mname"),""));
			mb.setMicon(micon);
			mb.setMiconno(miconno);
			mb.setMurl(StringTools.objectToString(request.getParameter("murl"),""));
			mb.setMremark(StringTools.objectToString(request.getParameter("mremark"),""));
			mb.setMstate(StringTools.objectToString(request.getParameter("mstate"),""));
			mb.setPhoneIcon(StringTools.objectToString(request.getParameter("phoneIcon"),""));
			mb.setWinIcon(StringTools.objectToString(request.getParameter("winIcon"),""));
			mb.setMremark(StringTools.objectToString(request.getParameter("mremark"),""));
			mb.setIconCls(StringTools.objectToString(request.getParameter("iconCls"),""));			
			mb.setSeqnum(NumberDealTools.stringTranceInt(StringTools.objectToString(request.getParameter("seqnum")),1));		
			int jobline = NumberDealTools.stringTranceInt(StringTools.objectToString(request.getParameter("jobline")));			
			int len = jobline+1;			
			List<MenuOperateBean> listoperates = new ArrayList<MenuOperateBean>();			
			MenuOperateBean mob = null;
			for(int i = 0; i < len; i++){				
				String opername = StringTools.objectToString(request.getParameter("name"+i),"");				
				if(!StringTools.isEmptyOrNull(opername)){
					String operId = StringTools.objectToString(request.getParameter("operId"+i),"");									
					String opercode = StringTools.objectToString(request.getParameter("code"+i),"");
					String operevent = StringTools.objectToString(request.getParameter("event"+i),"");
					String operestate = StringTools.objectToString(request.getParameter("state"+i),"");
					String opereseqnum = StringTools.objectToString(request.getParameter("operseqnum"+i),"");
					String opertype = StringTools.objectToString(request.getParameter("opertype"+i),"");
					String opereremark = StringTools.objectToString(request.getParameter("remark"+i),"");
					if(StringTools.isEmptyOrNull(operId)){
						operId = UUID.uuId();
					}
					String operIconCls = StringTools.objectToString(request.getParameter("iconCls"+i),"");
					if(StringTools.isEmptyOrNull(operIconCls) && "FUNTREE".equalsIgnoreCase(opertype)){
						operIconCls = "icon-add";
					}
					int seqnum1 = NumberDealTools.stringTranceInt(opereseqnum);
					seqnum1 = (seqnum1==0)?1:seqnum1;
					mob = new MenuOperateBean();
					mob.setOperId(operId);
					mob.setMenuId(menuId);
					mob.setOperatename(opername);
					mob.setOperatecode(opercode);
					mob.setOperateevent(operevent);
					mob.setOperatestate(NumberDealTools.stringTranceInt(operestate));
					mob.setOperseqnum(seqnum1);
					mob.setOpertype(opertype);
					mob.setOperateremark(opereremark);
					mob.setOperateIconCls(operIconCls);
					listoperates.add(mob);
				}
			}
			mb.setListoperates(listoperates);
			this.menuManager.deleteMenuOperate(menuId);
			boolean b = menuManager.updateMenu(mb);			
			if(b){
				writeText(response,KeyConstant.SUCCESS);
			}else{
				writeText(response,KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error("修改菜单信息异常："+e.toString());
			writeText(response,e.toString());				
		}
		return null;
	}
	
	/**
	 * <p>Description:删除菜单信息<p>
	 * @author LY
	 * @version 2014-9-16
	 * @modifier LY
	 * @modifiDate 2014-9-16
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=deleteMenu")
	public String deleteMenu(HttpServletRequest request,HttpServletResponse response){		
		String[] userIds = request.getParameterValues("id[]");	
		try {
			if(null==userIds || userIds.length==0){
				writeText(response, KeyConstant.EMPTY);
			}else{
				List<String> list = Arrays.asList(userIds);
				boolean b = this.menuManager.deleteMenu(list);		
				if(b){
					writeText(response, KeyConstant.SUCCESS);
				}else{
					writeText(response, KeyConstant.FAIL);
				}
			}			
		} catch (Exception e) {			
			log.error(""+e.toString());
			writeText(response, e.getMessage());
		}
		return null;
	}
}
